from django.contrib.admin.widgets import AdminFileWidget
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.conf import settings
from PIL import Image
import os


class AdminImageWidget(AdminFileWidget):
    """
    A FileField Widget that displays an image instead of a file path
    if the current file is an image.

    Could also be used with sorl.thumbnail to generate thumbnail images.

    Example:

    class FileUploadForm(forms.ModelForm):
        upload = forms.FileField(widget=AdminThumbnailWidget)

        class Meta:
            model = FileUpload

    class FileUploadAdmin(admin.ModelAdmin):
        form = FileUploadForm

    admin.site.register(FileUpload, FileUploadAdmin)

    """

    def render(self, name, value, attrs=None):
        output = []
        if value:
            file_path = '%s%s' % (settings.MEDIA_URL, value)
            try:            # is image
                Image.open(os.path.join(settings.MEDIA_ROOT, value))
                output.append('<a target="_blank" href="%s"><img src="%s" alt="%s" /></a><br />%s <a target="_blank" href="%s">%s</a><br />%s ' % \
                    (file_path, file_path, file_path, _('Currently:'),
                    file_path, value, _('Change:')))
            except IOError: # not image
                output.append('%s <a target="_blank" href="%s">%s</a> <br />%s ' % \
                    (_('Currently:'), file_path, value, _('Change:')))

        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))
